/*
 *    Copyright (c) 2006 ThoughtWorks, Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.thoughtworks.turtlemock.internal;

import junit.framework.AssertionFailedError;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class OperationMocker implements Operation {
    private static Map defaultPrimReturn = new HashMap();

    static {
        defaultPrimReturn.put(boolean.class, Boolean.FALSE);
        defaultPrimReturn.put(byte.class, new Byte((byte) 0));
        defaultPrimReturn.put(short.class, new Short((short) 0));
        defaultPrimReturn.put(int.class, new Integer(0));
        defaultPrimReturn.put(long.class, new Long(0));
        defaultPrimReturn.put(float.class, new Float(0));
        defaultPrimReturn.put(double.class, new Double(0));
    }

    private final BaseMock mock;

    public OperationMocker(BaseMock mock) {
        this.mock = mock;
    }

    public Object execute(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            Object returnValue = mock.mockingOperation(method.getName(), args);
            if (returnValue == null && method.getReturnType().isPrimitive()) {
                return defaultPrimReturn.get(method.getReturnType());
            }
            return returnValue;
        } catch (ExpectedException e) {
            return handleExpectedException(e, method);
        }
    }

    private Object handleExpectedException(ExpectedException e, Method method) throws Throwable {
        if (e.getInnerThrowable() instanceof RuntimeException) {
            throw e.getInnerThrowable();
        }
        if (isDeclared(method, e)) {
            throw e.getInnerThrowable();
        }
        String msg = "try to throw a checked exception not declared in the method signature: " + e.getInnerThrowable();
        throw new AssertionFailedError(msg + ", method: " + method.getName());
    }

    private boolean isDeclared(Method method, ExpectedException e) {
        Class[] exceptionTypes = method.getExceptionTypes();
        for (int i = 0; i < exceptionTypes.length; i++) {
            Class exceptionType = exceptionTypes[i];
            if (exceptionType.isInstance(e.getInnerThrowable())) {
                return true;
            }
        }
        return false;
    }
}
